package com.huabo.contract.service.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.Resource;

import com.hbfk.entity.TblAttachment;
import com.huabo.contract.config.DateBaseConfig;
import com.huabo.contract.util.MessageSender;
import org.springframework.stereotype.Service;

import com.hbfk.entity.DealUserToken;
import com.hbfk.entity.TblStaffUtil;
import com.hbfk.util.PageInfo;
import com.huabo.contract.oracle.entity.TblContractPlannode;
import com.huabo.contract.oracle.entity.TblCyhwUnit;
import com.huabo.contract.oracle.mapper.TblContractPlannodeMapper;
import com.huabo.contract.oracle.mapper.TblCyhwUnitMapper;
import com.huabo.contract.service.TblContractPlannodeService;
import com.huabo.contract.util.MailInfo;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;


@Service("TblContractPlannodeService")
@Slf4j
public class TblContractPlannodeServiceImpl implements TblContractPlannodeService {

    @Resource
    private TblContractPlannodeMapper tblContractPlannodeMapper;

    @Resource
    private TblCyhwUnitMapper tblCyhwUnitMapper;

    @Override
    public void findPlanNodeListForCollection(PageInfo<TblContractPlannode> pageInfo, TblContractPlannode node) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            pageInfo.setTlist(tblContractPlannodeMapper.findPlanNodeListForCollection(pageInfo, node));
            pageInfo.setTotalRecord(tblContractPlannodeMapper.selectCountByPageInfo(node));
            resultMap.put("code", "1");
            resultMap.put("msg", "访问接口成功");
            resultMap.put("data", pageInfo);
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            pageInfo.setTlist(tblContractPlannodeMapper.findPlanNodeListForCollection(pageInfo, node));
            pageInfo.setTotalRecord(tblContractPlannodeMapper.selectCountByPageInfo(node));
            resultMap.put("code", "1");
            resultMap.put("msg", "访问接口成功");
            resultMap.put("data", pageInfo);
        }

    }

    @Override
    public void findPlanNodeListForPayment(PageInfo<TblContractPlannode> pageInfo, TblContractPlannode node) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            pageInfo.setTlist(tblContractPlannodeMapper.findPlanNodeListForPayment(pageInfo, node));
            pageInfo.setTotalRecord(tblContractPlannodeMapper.findPlanNodeListForPaymentCount(node));
            resultMap.put("code", "1");
            resultMap.put("msg", "访问接口成功");
            resultMap.put("data", pageInfo);
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            pageInfo.setTlist(tblContractPlannodeMapper.findPlanNodeListForPayment(pageInfo, node));
            pageInfo.setTotalRecord(tblContractPlannodeMapper.findPlanNodeListForPaymentCount(node));
            resultMap.put("code", "1");
            resultMap.put("msg", "访问接口成功");
            resultMap.put("data", pageInfo);
        }
    }


    @Override
    public Map<String, Object> saveContractPlannode(TblContractPlannode node, Integer contractId,Integer jbunitid, Integer jbstaffid) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            try {
                if (node.getNodemoney() != null) {
                    BigDecimal contractMoney = this.tblCyhwUnitMapper.findContractMoneyByContractId(contractId);
                    BigDecimal sumMoney = this.tblContractPlannodeMapper.findeSumMoneyByContractId(contractId, node.getNodeid());
                    if (contractMoney.compareTo(sumMoney.add(node.getNodemoney())) == -1) {
                        resultMap.put("code", "0");
                        resultMap.put("msg", "合同阶段总金额大于合同金额！");
                        return resultMap;
                    }
                }
//            Date startDate = DateUtils.parse(node.getPlanstartdate(), "yyyy-MM-dd");
//            Date endDate = DateUtils.parse(date2, "yyyy-MM-dd");
//            if(date3 != null && !"".equals(date3)) {
//                Date planDate = DateUtils.parse(date3, "yyyy-MM-dd");
//                node.setNodeplanpaydate(planDate);
//            }
                node.setProjectid(new BigDecimal(contractId));
//            node.setPlanstartdate(startDate);
//            node.setPlanenddate(endDate);
                if (jbstaffid != null) {
                    node.setDispatchstaff(new BigDecimal(jbstaffid));
                }
                if (jbunitid != null) {
                    node.setDispatchdept(new BigDecimal(jbunitid));
                }
                if (node.getNodeid() != null) {
                    this.tblContractPlannodeMapper.updateContractPlannode(node);
                } else {
                    this.tblContractPlannodeMapper.saveContractPlannode(node);
                }

            } catch (Exception e) {
                resultMap.put("code", "-1");
                resultMap.put("msg", "保存失败");
                return resultMap;
            }
            resultMap.put("code", "1");
            resultMap.put("msg", "保存成功");
            resultMap.put("data", node);
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            try {
                if (node.getNodemoney() != null) {
                    BigDecimal contractMoney = this.tblCyhwUnitMapper.findContractMoneyByContractId(contractId);
                    BigDecimal sumMoney = this.tblContractPlannodeMapper.findeSumMoneyByContractId(contractId, node.getNodeid());
                    if (contractMoney.compareTo(sumMoney.add(node.getNodemoney())) == -1) {
                        resultMap.put("code", "0");
                        resultMap.put("msg", "合同阶段总金额大于合同金额！");
                        return resultMap;
                    }
                }
//            Date startDate = DateUtils.parse(node.getPlanstartdate(), "yyyy-MM-dd");
//            Date endDate = DateUtils.parse(date2, "yyyy-MM-dd");
//            if(date3 != null && !"".equals(date3)) {
//                Date planDate = DateUtils.parse(date3, "yyyy-MM-dd");
//                node.setNodeplanpaydate(planDate);
//            }
                node.setProjectid(new BigDecimal(contractId));
//            node.setPlanstartdate(startDate);
//            node.setPlanenddate(endDate);
                if (jbstaffid != null) {
                    node.setDispatchstaff(new BigDecimal(jbstaffid));
                }
                if (jbunitid != null) {
                    node.setDispatchdept(new BigDecimal(jbunitid));
                }
                if (node.getNodeid() != null) {
                    this.tblContractPlannodeMapper.updateContractPlannode(node);
                } else {
                    this.tblContractPlannodeMapper.saveContractPlannode(node);
                }

            } catch (Exception e) {
                resultMap.put("code", "-1");
                resultMap.put("msg", "保存失败");
                return resultMap;
            }
            resultMap.put("code", "1");
            resultMap.put("msg", "保存成功");
            resultMap.put("data", node);
            return resultMap;
        }
    }

    @Override
    public Map<String, Object> removeContractPlannode(Integer nodeId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            try {
                this.tblContractPlannodeMapper.removeContractPlannode(nodeId);
            } catch (Exception e) {
                resultMap.put("code", "-1");
                resultMap.put("msg", "删除失败");
                return resultMap;
            }
            resultMap.put("code", "1");
            resultMap.put("msg", "删除成功");
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            try {
                this.tblContractPlannodeMapper.removeContractPlannode(nodeId);
            } catch (Exception e) {
                resultMap.put("code", "-1");
                resultMap.put("msg", "删除失败");
                return resultMap;
            }
            resultMap.put("code", "1");
            resultMap.put("msg", "删除成功");
            return resultMap;
        }
    }


    @Override
    public Map<String, Object> sendTipEmail(TblCyhwUnit tcu, String content, String date, String token, String staffId) throws Exception {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date nowDate = new Date();
            Date tipDate = fmt.parse(date);
            long timelong = tipDate.getTime() - nowDate.getTime();
            if (timelong <= 0) {
                resultMap.put("code", "2");
                resultMap.put("msg", "提醒时间不能小于当前系统时间");
                return resultMap;
            }
            TblStaffUtil staff = DealUserToken.parseUserToken(token);
            if (staff == null) {
                resultMap.put("code", "0");
                resultMap.put("msg", "用户已失效！");
                return resultMap;
            }
            //this.tblContractPlannodeMapper.sendTipEmail(tcu,timelong,staff,content);
            Timer timer = new Timer();
            final String title;
            if ("无".equals(tcu.getDctype())) {
                title = tcu.getContractname() + "提醒";
            } else {
                title = tcu.getContractname() + tcu.getDctype() + "提醒";
            }
            final String str = "<p>合同名称：" + tcu.getContractname() + "</p>" + "<p>合同编号：" + tcu.getContractno() + "</p>";
            TimerTask task = new TimerTask() {
                public void run() {
                    String serverHost = "smtp.qq.com";
                    String user = "1421869153@qq.com";  //用户名
                    String password = "oygxczsevfqghicf";  //密码
                    String fromAddress = "1421869153@qq.com";  //邮件地址
                    String fileName = "";
                    List<String> receiver = new ArrayList<String>();
                    receiver.add(staff.getEmail());
                    List<String> ccReceiver = new ArrayList<String>();
                    MailInfo mailInfo = new MailInfo(serverHost, user, password, fromAddress, title, str + content, receiver, ccReceiver, fileName);
                    try {
                        MessageSender.sendHtmlMail(mailInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            // 延迟 1s 打印 wtf 一次
            timer.schedule(task, timelong);
            resultMap.put("code", "1");
            resultMap.put("msg", "设置成功！");
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date nowDate = new Date();
            Date tipDate = fmt.parse(date);
            long timelong = tipDate.getTime() - nowDate.getTime();
            if (timelong <= 0) {
                resultMap.put("code", "2");
                resultMap.put("msg", "提醒时间不能小于当前系统时间");
                return resultMap;
            }
            TblStaffUtil staff = DealUserToken.parseUserToken(token);
            if (staff == null) {
                resultMap.put("code", "0");
                resultMap.put("msg", "用户已失效！");
                return resultMap;
            }
            //this.tblContractPlannodeMapper.sendTipEmail(tcu,timelong,staff,content);
            Timer timer = new Timer();
            final String title;
            if ("无".equals(tcu.getDctype())) {
                title = tcu.getContractname() + "提醒";
            } else {
                title = tcu.getContractname() + tcu.getDctype() + "提醒";
            }
            final String str = "<p>合同名称：" + tcu.getContractname() + "</p>" + "<p>合同编号：" + tcu.getContractno() + "</p>";
            TimerTask task = new TimerTask() {
                public void run() {
                    String serverHost = "smtp.qq.com";
                    String user = "1421869153@qq.com";  //用户名
                    String password = "oygxczsevfqghicf";  //密码
                    String fromAddress = "1421869153@qq.com";  //邮件地址
                    String fileName = "";
                    List<String> receiver = new ArrayList<String>();
                    receiver.add(staff.getEmail());
                    List<String> ccReceiver = new ArrayList<String>();
                    MailInfo mailInfo = new MailInfo(serverHost, user, password, fromAddress, title, str + content, receiver, ccReceiver, fileName);
                    try {
                        MessageSender.sendHtmlMail(mailInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            // 延迟 1s 打印 wtf 一次
            timer.schedule(task, timelong);
            resultMap.put("code", "1");
            resultMap.put("msg", "设置成功！");
            return resultMap;
        }
    }

    @Override
    public Map<String, Object> findWorkableContractNodeByPageInfo(Integer contractId, Integer pageNumber, Integer pageSize, String token,TblContractPlannode node) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            TblStaffUtil user = null;
            try {
                user = DealUserToken.parseUserToken(token);
                if (user == null) {
                    resultMap.put("code", "0");
                    resultMap.put("msg", "用户已失效！");
                    return resultMap;
                }
                PageInfo<TblContractPlannode> pageInfo = new PageInfo<TblContractPlannode>();
                pageInfo.setCurrentPage(pageNumber);
                pageInfo.setPageSize(pageSize);
                node.setProjectid(new BigDecimal(contractId));
                pageInfo.setCondition(node);
                pageInfo.setTlist(tblContractPlannodeMapper.findContractNodeListByPageInfo(pageInfo));
                pageInfo.setTotalRecord(tblContractPlannodeMapper.findCountContractNodeByPageInfo(pageInfo));
                resultMap.put("code", "1");
                resultMap.put("msg", "成功！");
                resultMap.put("data", pageInfo);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            TblStaffUtil user = null;
            try {
                user = DealUserToken.parseUserToken(token);
                if (user == null) {
                    resultMap.put("code", "0");
                    resultMap.put("msg", "用户已失效！");
                    return resultMap;
                }
                PageInfo<TblContractPlannode> pageInfo = new PageInfo<TblContractPlannode>();
                pageInfo.setCurrentPage(pageNumber);
                pageInfo.setPageSize(pageSize);
                node.setProjectid(new BigDecimal(contractId));
                pageInfo.setCondition(node);
                pageInfo.setTlist(tblContractPlannodeMapper.findContractNodeListByPageInfo(pageInfo));
                pageInfo.setTotalRecord(tblContractPlannodeMapper.findCountContractNodeByPageInfo(pageInfo));
                resultMap.put("code", "1");
                resultMap.put("msg", "成功！");
                resultMap.put("data", pageInfo);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        }

    }

    @Override
    public Map<String, Object> modifyPlanNodeStatus(Integer nodeId, Integer planStatus, String feedback) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            this.tblContractPlannodeMapper.modifyPlanNodeStatus(nodeId, planStatus, feedback);
            resultMap.put("code", "1");
            resultMap.put("msg", "成功！");
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            this.tblContractPlannodeMapper.modifyPlanNodeStatus(nodeId, planStatus, feedback);
            resultMap.put("code", "1");
            resultMap.put("msg", "成功！");
            return resultMap;
        }
    }

    @Override
    public Map<String, Object> selectById(Integer nodeId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            TblContractPlannode node = this.tblContractPlannodeMapper.selectByPlanId(nodeId);
            resultMap.put("code", "1");
            resultMap.put("msg", "成功！");
            resultMap.put("data", node);
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            TblContractPlannode node = this.tblContractPlannodeMapper.selectByPlanId(nodeId);
            resultMap.put("code", "1");
            resultMap.put("msg", "成功！");
            resultMap.put("data", node);
            return resultMap;
        }
    }

    @Override
    public TblContractPlannode findWriteContractPlanNode(Integer planId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return tblContractPlannodeMapper.findWriteContractPlanNode(planId);
        } else {
            return tblContractPlannodeMapper.findWriteContractPlanNode(planId);
        }
    }

    @Override
    public List<TblAttachment> findeWriteContractPlanFileInfo(Integer planId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return tblContractPlannodeMapper.findeWriteContractPlanFileInfo(planId);
        } else {
            return tblContractPlannodeMapper.findeWriteContractPlanFileInfo(planId);
        }
    }

    @Override
    public void saveContractPlannodeTcp(TblContractPlannode tcp) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            tblContractPlannodeMapper.saveContractPlannode(tcp);
        } else {
            tblContractPlannodeMapper.saveContractPlannode(tcp);
        }
    }

    @Override
    public void updateTcp(TblContractPlannode tcp) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            tblContractPlannodeMapper.updateContractPlannode(tcp);
        } else {
            tblContractPlannodeMapper.updateContractPlannode(tcp);
        }
    }

    @Override
    public Map<String, Object> findPlannodeListById(Integer contractId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            List<TblContractPlannode> nodeList = this.tblContractPlannodeMapper.findPlanNodeListByContractId(new BigDecimal(contractId));
            resultMap.put("code", "1");
            resultMap.put("msg", "成功！");
            resultMap.put("data", nodeList);
            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            List<TblContractPlannode> nodeList = this.tblContractPlannodeMapper.findPlanNodeListByContractId(new BigDecimal(contractId));
            resultMap.put("code", "1");
            resultMap.put("msg", "成功！");
            resultMap.put("data", nodeList);
            return resultMap;
        }
    }

    @Override
    public TblContractPlannode findPlannodeById(BigDecimal nodeid) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            return this.tblContractPlannodeMapper.findPlannodeById(nodeid);
        } else {
            return this.tblContractPlannodeMapper.findPlannodeById(nodeid);
        }
    }

    
    @Override
    public Map<String, Object> findPlannodeListByContractId(Integer contractId) {
        if(DateBaseConfig.DATABASETYPE.equals("Oracle")) {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            if (contractId != null && contractId > 0) {
                List<JSONObject> nodeList = this.tblContractPlannodeMapper.findPlanNodeListById(new BigDecimal(contractId));
                List<JSONObject> nodeList2 = new ArrayList<JSONObject>();
                for (JSONObject j : nodeList) {
                    JSONObject i = new JSONObject();
                    Double nodemoney = 0.0;
                    if (j.get("NODEMONEY") != null) {
                        nodemoney = Double.parseDouble(j.get("NODEMONEY").toString());
                    }
                    Double yfnodemoney = 0.0;
                    if (j.get("YFNODEMONEY") != null) {
                        yfnodemoney = Double.parseDouble(j.get("YFNODEMONEY").toString());
                    }
                    Double wfnodemoney = nodemoney - yfnodemoney;
                    i.put("nodeId", j.get("NODEID") != null ? j.get("NODEID").toString() : "");
                    i.put("nodecontent", j.get("NODECONTENT") != null ? j.get("NODECONTENT").toString() : "");
                    i.put("planstartdate", j.get("PLANSTARTDATE") != null ? j.get("PLANSTARTDATE").toString() : "");
                    i.put("planenddate", j.get("PLANENDDATE") != null ? j.get("PLANENDDATE").toString() : "");
                    i.put("nodepost", j.get("NODEPOST") != null ? j.get("NODEPOST").toString() : "");
                    i.put("nodemoney", j.get("NODEMONEY") != null ? j.get("NODEMONEY").toString() : 0);
                    i.put("wfnodemoney", wfnodemoney);

                    nodeList2.add(i);
                }
                resultMap.put("code", "0");
                resultMap.put("msg", "成功！");
                resultMap.put("data", nodeList2);
            } else {
                resultMap.put("code", "1");
                resultMap.put("msg", "合同主键未传递！");
            }


            return resultMap;
        } else {
            Map<String, Object> resultMap = new HashMap<String, Object>(0);
            if (contractId != null && contractId > 0) {
                List<JSONObject> nodeList = this.tblContractPlannodeMapper.findPlanNodeListById(new BigDecimal(contractId));
                List<JSONObject> nodeList2 = new ArrayList<JSONObject>();
                for (JSONObject j : nodeList) {
                    JSONObject i = new JSONObject();
                    Double nodemoney = 0.0;
                    if (j.get("NODEMONEY") != null) {
                        nodemoney = Double.parseDouble(j.get("NODEMONEY").toString());
                    }
                    Double yfnodemoney = 0.0;
                    if (j.get("YFNODEMONEY") != null) {
                        yfnodemoney = Double.parseDouble(j.get("YFNODEMONEY").toString());
                    }
                    Double wfnodemoney = nodemoney - yfnodemoney;
                    i.put("nodeId", j.get("NODEID") != null ? j.get("NODEID").toString() : "");
                    i.put("nodecontent", j.get("NODECONTENT") != null ? j.get("NODECONTENT").toString() : "");
                    i.put("planstartdate", j.get("PLANSTARTDATE") != null ? j.get("PLANSTARTDATE").toString() : "");
                    i.put("planenddate", j.get("PLANENDDATE") != null ? j.get("PLANENDDATE").toString() : "");
                    i.put("nodepost", j.get("NODEPOST") != null ? j.get("NODEPOST").toString() : "");
                    i.put("nodemoney", j.get("NODEMONEY") != null ? j.get("NODEMONEY").toString() : 0);
                    i.put("wfnodemoney", wfnodemoney);

                    nodeList2.add(i);
                }
                resultMap.put("code", "0");
                resultMap.put("msg", "成功！");
                resultMap.put("data", nodeList2);
            } else {
                resultMap.put("code", "1");
                resultMap.put("msg", "合同主键未传递！");
            }


            return resultMap;
        }
    }

}
